<script setup>
import {
  auditStudentInternshipMaterialApi,
  getStudentWeeklyApi,
  submitStudentWeeklyApi,
  uploadStudentInternshipMaterialsApi
} from '@/api/job'
import Table from '@/components/practice/table.vue'
import { showMessage, showStatusMessage } from '@/utils/common/showMessage'
import { ref, watch, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import WangEditor from '@/components/practice/wangEditor.vue'
import { dayFormat } from '@/utils/common/dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { bus } from '@/utils/common/mitt'
import { getPracticeApplyByStudentApi } from '@/api/baseData'

// 常量定义
const WEEKLY_COLUMNS = [
  { prop: 'weekly', label: '周记' },
  { prop: 'create_time', label: '提交时间', display: 'tag' },
  { prop: 'status', label: '审核状态', display: 'tag' },
  { prop: 'feedbackDesc', label: '结果反馈', display: 'feedback' }
]

const WEEKLY_OPTIONS = [
  { label: '查看与修改', type: 'success', prop: 'viewWeekly' },
  { label: '提交', type: 'warning', prop: 'submitWeekly' }
]

const EDITOR_OPTIONS = [
  { prop: 'task', desc: '本周完成任务' },
  { prop: 'plan', desc: '下周计划' }
]

// 状态管理
const router = useRouter()
const userStore = useUserStore()
const formData = ref({ desc: '' })
const tableData = ref([])
const intershipType = ref(null)
const isShowContent = ref(false)
const weeklyTypeNum = ref(null)
const dialogViewVisible = ref(false)
const editorRef = ref(null)
const dataEditor = ref({ task: '', plan: '' })
const submitWeeklyData = ref(null)
const docPreview = ref('')

// 计算属性
const userInfo = computed(() => userStore.userInfo)

// 方法定义
const reset = () => {
  getTableData()
  pagizationRef.value?.reset()
  selectFormRef.value?.reset()
}

const getTableData = async (data = {}) => {
  try {
    const res2 = await getPracticeApplyByStudentApi({
      account: userInfo.value.account
    })
    
    if (res2.status === 1) {
      isShowContent.value = true
      showStatusMessage(res2)
      return
    }

    intershipType.value = res2.data.map(item => item.type)
    
    const res = await getStudentWeeklyApi({
      ...data,
      class: userInfo.value.class,
      name: userInfo.value.name,
      account: userInfo.value.account,
      type: intershipType.value
    })

    if (res.status === 1) {
      showStatusMessage(res)
      return
    }

    weeklyTypeNum.value = res.weeklyTypeNum
    tableData.value = [...res.data]
  } catch (error) {
    ElMessage.error('获取数据失败，请稍后重试')
    console.error('获取数据失败:', error)
  }
}

const handleDialogViewClose = () => {
  docPreview.value = ''
  dataEditor.value = {}
  submitWeeklyData.value = {}
  dialogViewVisible.value = false
}

const handletTableSubmitWeeklyJournal = (data) => {
  dataEditor.value = {
    task: data.task,
    plan: data.plan,
    type: data.type,
    weekly: data.weekly
  }
  submitWeeklyData.value = data
  dialogViewVisible.value = true
}

const handletTableviewWeekly = (data) => {
  if (!data.plan || !data.task) {
    ElMessage.error('暂未提交内容')
    return
  }
  
  submitWeeklyData.value = data
  dataEditor.value.plan = data.plan
  dataEditor.value.task = data.task
  dialogViewVisible.value = true
}

const handletTableFeedbackDesc = (data) => {
  ElMessageBox.alert(data.feedbackDesc, '查看反馈', {
    confirmButtonText: '确认'
  })
}

const handleTable = (data, type) => {
  console.log(data);
  
  const handlers = {
    submitWeekly: handletTableSubmitWeeklyJournal,
    viewWeekly: handletTableviewWeekly,
    feedbackDesc: handletTableFeedbackDesc
  }
  
  handlers[type]?.(data)
}

const handleEditorSubmit = async (data) => {
  try {
    const formData = {
      account: userInfo.value.account,
      class: userInfo.value.class,
      name: userInfo.value.name,
      weekly: submitWeeklyData.value.weekly,
      task: data.task,
      plan: data.plan,
      create_time: dayFormat(new Date()),
      type: data.type
    }
    
    const res = await submitStudentWeeklyApi(formData)
    showStatusMessage(res)
    await getTableData()
    dialogViewVisible.value = false
  } catch (error) {
    ElMessage.error('提交失败，请稍后重试')
    console.error('提交失败:', error)
  }
}

const handleEditor = (type, data) => {
  if (type === 'cancel') {
    dialogViewVisible.value = false
    submitWeeklyData.value = {}
  } else if (type === 'submit') {
    handleEditorSubmit(data)
  }
}

// 监听器
watch(dialogViewVisible, (newValue) => {
  if (!newValue) {
    handleDialogViewClose()
  }
})

// 生命周期钩子
onMounted(() => {
  getTableData()
})
</script>

<template>
  <div class="license-wrapper">
    <div v-if="isShowContent" class="no-data">
      <div class="no-data-icon"></div>
      <p>暂无通过的实习申请，请等待或上传实习申请</p>
    </div>
    
    <div v-else class="user-content">
      <div 
        v-for="(item, index) in intershipType" 
        :key="index" 
        class="journal-block"
      >
        <div class="title">
          {{ item }}的实习周记列表
          <span class="weekly-type-num">
            需提交周记次数：{{ weeklyTypeNum[index] }}
          </span>
        </div>
        
        <Table
          :tableData="tableData[index]"
          :columns="WEEKLY_COLUMNS"
          :options="WEEKLY_OPTIONS"
          @handleTable="handleTable"
        >
          <template #firstColumn>
            <el-table-column 
              type="index" 
              label="提交次序" 
              width="100" 
              align="center" 
            />
          </template>
        </Table>
      </div>

      <div v-if="dialogViewVisible" class="weekly-content">
        <div class="weekly-header">
          <div class="title-icon" @click="handleDialogViewClose">
            <el-icon :size="24" class="close-icon"><Close /></el-icon>
          </div>
        </div>
        
        <div class="weekly-editor">
          <WangEditor
            ref="editorRef"
            :dataEditor="dataEditor"
            :editorOpt="EDITOR_OPTIONS"
            @handleEditor="handleEditor"
            class="editor-container"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.license-wrapper {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: #f5f7fa;

  .no-data {
    // @include flex-center;
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: 400px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
    border-radius: 12px;
    margin: 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    animation: fadeIn 0.8s ease-out;
    
    .no-data-icon {
      width: 120px;
      height: 120px;
      background-image: url('@/assets/images/no-data.svg');
      background-size: contain;
      background-repeat: no-repeat;
      margin-bottom: 25px;
      animation: float 3s ease-in-out infinite;
    }

    p {
      font-size: 20px;
      color: #2c3e50;
      font-weight: 500;
      letter-spacing: 1px;
    }
  }

  .user-content {
    width: 100%;
    padding: 20px 50px;
    
    .journal-block {
      margin-top: 32px;
      background: #fff;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
      transition: transform 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      .title {
        font-size: 22px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 25px;
        padding: 15px 25px;
        background: #ffffff;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
        border-left: 4px solid #409EFF;
      }
      
      .weekly-type-num {
        font-size: 14px;
        color: #666;
        background: linear-gradient(135deg, #f6f8fa 0%, #e9ecef 100%);
        padding: 6px 15px;
        border-radius: 20px;
        display: inline-flex;
        align-items: center;
        font-weight: 500;
        
        &::before {
          content: '📝';
          margin-right: 8px;
        }
      }
    }
  }

  .weekly-content {
    position: fixed;
    top: 5vh;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    max-width: 1200px;
    max-height: 80vh;
    overflow: scroll;
    z-index: 1000;
    background-color: #fff;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
    
    .weekly-header {
      position: relative;
      margin-bottom: 20px;
      
      .title-icon {
        position: absolute;
        right: 0;
        top: 0;
        cursor: pointer;
        padding: 8px;
        border-radius: 50%;
        transition: background-color 0.3s;
        
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}
</style>
